package utils

import (
	"bytes"
	"fmt"
	"runtime"
	"strconv"
	"strings"
)

func GetCurrentGoRoutineID() uint64 {

	b := make([]byte, 64)
	b = b[:runtime.Stack(b, false)]
	b = bytes.TrimPrefix(b, []byte("goroutine "))
	b = b[:bytes.IndexByte(b, ' ')]
	n, _ := strconv.ParseUint(string(b), 10, 64)
	return n
}

func allStack() []byte {
	buf := make([]byte, 1024)
	for {
		n := runtime.Stack(buf, true)
		if n < len(buf) {
			return buf[:n]
		}
		buf = make([]byte, 2*len(buf))
	}
}

func GetGoroutineStack(n uint64) string {
	stackstr := string(allStack())
	nstr := fmt.Sprintf("%d", n)
	stacks := strings.Split(stackstr, "goroutine")
	for _, v := range stacks {
		str := Trim(v)
		if len(str) > len(nstr) {
			if strings.Compare(nstr, string(str[:len(nstr)])) == 0 {
				return v
			}
		}
	}

	return ""
}
